{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "#### ICS 104 - Introduction to Programming in Python and C  \n",
    "# Loops\n",
    "## Reading Assignment\n",
    "- Chapter 4 Sections 1, 2, 3, 5, 6, 7, 8 and 9."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Chapter Learning Outcomes\n",
    "### At the end of this chapter, you will be able to"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- implement while and for loops\n",
    "- become familiar with common loop algorithms\n",
    "- understand nested loops\n",
    "- process strings\n",
    "- generate random numbers"
   ]
  },
  {
   "attachments": {
    "fig1.PNG": {
     "image/png": "[encoded data, 538944 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Loops\n",
    "- In a <font color='blue'>**loop**</font>, a part of a program is repeated over and over until a specific goal is reached. \n",
    "- Loops are important for calculations that require repeated steps, and for processing input consisting of many data items.\n",
    "\n",
    "![fig1.PNG](attachment:fig1.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "- For example, You put $10,000 into a bank account that earns 5 percent interest per year. \n",
    "- How many years does it take for the account balance to be double the original investment?"
   ]
  },
  {
   "attachments": {
    "fig2.PNG": {
     "image/png": "[encoded data, 64680 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![fig2.PNG](attachment:fig2.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Question: How we can implement the \"Repeat steps while the balance is less than $20,000?\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Answer: Using the while loop statement"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "`while` *condition* `:`\n",
    "```\n",
    "   statements  \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "while balance < TARGET :\n",
    "    year = year + 1\n",
    "    interest = balance * RATE / 100\n",
    "    balance = balance + interest"
   ]
  },
  {
   "attachments": {
    "fig4.PNG": {
     "image/png": "[encoded data, 168332 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "![fig4.PNG](attachment:fig4.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "- As long as the condition remains true, the statements\n",
    "inside the <font color='blue'>**while**</font> statement are executed. \n",
    "- This statement block is called the <font color='blue'>**body**</font> of the while statement."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For example, we want to increment the year counter and add interest while the balance is less than the target balance of $20,000:"
   ]
  },
  {
   "attachments": {
    "fig3.PNG": {
     "image/png": "[encoded data, 25932 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "![fig3.PNG](attachment:fig3.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "## Execution of the Loop"
   ]
  },
  {
   "attachments": {
    "ch04fig13.PNG": {
     "image/png": "[encoded data, 227844 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch04fig13.PNG](attachment:ch04fig13.PNG)"
   ]
  },
  {
   "attachments": {
    "ch04fig14.PNG": {
     "image/png": "[encoded data, 179424 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch04fig14.PNG](attachment:ch04fig14.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "## Event-Controlled Loops"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "#  This program computes the time required to double an investment.\n",
    "# Create constant variables.\n",
    "RATE = 5.0\n",
    "INITIAL_BALANCE = 10000.0\n",
    "TARGET = 2 * INITIAL_BALANCE\n",
    "      \n",
    "# Initialize variables used with the loop.\n",
    "balance = INITIAL_BALANCE\n",
    "year = 0\n",
    "\n",
    "# Count the years required for the investment to double.\n",
    "while balance < TARGET :\n",
    "   year = year + 1\n",
    "   interest = balance * RATE / 100\n",
    "   balance = balance + interest\n",
    "   \n",
    "# Print the results.   \n",
    "print(\"The investment doubled after\", year, \"years.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "## Count-Controlled Loops"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- A while loop that is controlled by a counter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "counter = 1                 # Initialize the counter\n",
    "\n",
    "while counter <= 10 :       # Check the counter\n",
    "    print(counter)\n",
    "    counter = counter + 1   # Update the loop variable"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop - Student Activity\n",
    "- What does the following loop print?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "4\n",
      "8\n",
      "16\n",
      "32\n",
      "64\n",
      "128\n"
     ]
    }
   ],
   "source": [
    "n =1\n",
    "while n < 100:\n",
    "    n = 2* n\n",
    "    print(n)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop - Student Activity\n",
    "- What does the following loop print?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 1\n",
      "2 3\n",
      "3 6\n",
      "4 10\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "total = 0\n",
    "while total < 10:\n",
    "    i = i + 1\n",
    "    total = total + i\n",
    "    print(i,total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "The while Loop - Student Activity\n",
    "- What does the following loop print?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "i = 0\n",
    "total = 0\n",
    "while total < 0:\n",
    "    i = i + 1\n",
    "    total = total - i\n",
    "    print(i,total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The While Loop\n",
    "- We want to write loops that read and process a sequence of input values. \n",
    "- A <font color='blue'>**sentinel value**</font> denotes the end of a data set, but it is not part of the data. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- We want to write a program that computes the average of a set of salary values. \n",
    "- We will use any negative value as the sentinel. \n",
    "    - An employee would surely not work for a negative salary. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "#  This program prints the average of salary values that are terminated with \n",
    "#  a sentinel.\n",
    "\n",
    "# Initialize variables to maintain the running total and count.\n",
    "total = 0.0\n",
    "count = 0\n",
    "\n",
    "# Initialize salary to any non-sentinel value.\n",
    "salary = 0.0\n",
    "\n",
    "# Process data until the sentinel is entered.\n",
    "while salary >= 0.0 :\n",
    "   salary = float(input(\"Enter a salary or a negative value to finish: \"))\n",
    "   if salary >= 0.0 :\n",
    "      total = total + salary\n",
    "      count = count + 1\n",
    "   \n",
    "# Compute and print the average salary.\n",
    "if count > 0 :\n",
    "   average = total / count\n",
    "   print(\"Average salary is\", average)\n",
    "else :\n",
    "   print(\"No data was entered.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Common Loop Algorithms\n",
    "- Sum and Average Values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "total = 0.0\n",
    "inputStr = input(\"Enter value: \")\n",
    "while inputStr !=\"\":\n",
    "    value = float(inputStr)\n",
    "    total = total + value\n",
    "    inputStr = input(\"Enter value: \")\n",
    "print(\"Sum: \",total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Common Loop Algorithms\n",
    "- Sum and Average Value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "total = 0.0\n",
    "count = 0\n",
    "inputStr = input(\"Enter value: \")\n",
    "while inputStr !=\"\":\n",
    "    value = float(inputStr)\n",
    "    total = total + value\n",
    "    count = count + 1\n",
    "    inputStr = input(\"Enter value: \")\n",
    "if count > 0:\n",
    "    average = total/count\n",
    "else:\n",
    "    average = 0.0\n",
    "print(\"Average: \",average)"
   ]
  },
  {
   "attachments": {
    "ch04fig6.PNG": {
     "image/png": "[encoded data, 238356 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Common Loop Algorithms\n",
    "- Counting Matches - You want to count how many negative values are included in a sequence of integers. \n",
    "- Keep a <font color='blue'>**counter**</font>, a variable that is initialized with 0 and incremented whenever there is a match. \n",
    "![ch04fig6.PNG](attachment:ch04fig6.PNG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "negatives = 0\n",
    "inputStr = input(\"Enter value: \")\n",
    "while inputStr !=\"\":\n",
    "    value = int(inputStr)\n",
    "    if value < 0:\n",
    "        negatives = negatives + 1\n",
    "    inputStr = input(\"Enter value: \")\n",
    "print(\"There were\", negatives,\"negative values.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The `for` Loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Uses of a `for` loop:\n",
    "    - The `for` loop can be used to iterate over the contents of any container.\n",
    "    - A container is an object (like a string) that contains or stores a collection of elements.\n",
    "    - A string is a container that stores a sequence of characters. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The `for` Loop\n",
    "- Suppose we want to print a string, with one character per line.\n",
    "- We cannot simply print the string using the <font color='blue'>**print**</font> function.\n",
    "- Instead, we need to iterate over the characters in the string and print each character individually."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- An important difference between the while loop and the for loop:\n",
    "    - In the while loop, the index variable i is assigned 0, 1 and so on.\n",
    "    - In the for loop with a string container `stateName`, the element variable is assigned `stateName[0]`, `stateName[1]`, and so on. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "stateName = \"Virginia\"\n",
    "for letter in stateName :\n",
    "    print(letter)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The loop body is executed for each character in the string `stateName`, starting with the first character. \n",
    "- At the beginning of each loop iteration, the next character is assigned to the variable letter. \n",
    "- Then the loop body is executed."
   ]
  },
  {
   "attachments": {
    "fig5.PNG": {
     "image/png": "[encoded data, 81184 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "![fig5.PNG](attachment:fig5.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The `for` Loop\n",
    "- Can we write this program using a <font color='blue'>**while**</font> loop?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "stateName = \"Virginia\"\n",
    "for letter in stateName :\n",
    "    print(letter)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "V\n",
      "i\n",
      "r\n",
      "g\n",
      "i\n",
      "n\n",
      "i\n",
      "a\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "stateName = \"Virginia\"\n",
    "while i < len(stateName):\n",
    "    letter = stateName[i]\n",
    "    print(letter)\n",
    "    i = i + 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The for Loop\n",
    "- The <font color='blue'>**for**</font> loop can be used with the `range` function to iterate over a range of integer values.\n",
    "- When we write `range(i,j)`, what are the range values (assuming that $i < j$?) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n"
     ]
    }
   ],
   "source": [
    "for i in range(1,10):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "# Student Activity\n",
    "- Write an equivalent while loop for the previous example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "cell_style": "center",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n"
     ]
    }
   ],
   "source": [
    "i = 1\n",
    "while i < 10:\n",
    "    print(i)\n",
    "    i = i + 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The range Function\n",
    "- You can use a for loop as a count-controlled loop to iterate over a range of integer values. \n",
    "- We use the `range` function for generating a sequence of integers that are less than the argument that can be used with the for loop. "
   ]
  },
  {
   "attachments": {
    "ch04fig15.PNG": {
     "image/png": "[encoded data, 489000 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch04fig15.PNG](attachment:ch04fig15.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# The for Loop - Student Activity\n",
    "- Use the <font color='blue'>**for**</font> loop to print only the odd values between 1 and 10 using the <font color='blue'>**range**</font> function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "for i in range(1,10,2):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Nested Loop\n",
    "- When the body of a loop contains another loop, the loops are nested. \n",
    "- A typical use of nested loops is printing a table with rows and colums."
   ]
  },
  {
   "attachments": {
    "ch04fig7.PNG": {
     "image/png": "[encoded data, 19712 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- For example, we will print the powers of x as in the following table.\n",
    "![ch04fig7.PNG](attachment:ch04fig7.PNG)"
   ]
  },
  {
   "attachments": {
    "ch04fig8.PNG": {
     "image/png": "[encoded data, 13728 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Nested Loop\n",
    "- The pseudocode for printing the table is as follows:\n",
    "![ch04fig8.PNG](attachment:ch04fig8.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- How do you print a table row?"
   ]
  },
  {
   "attachments": {
    "ch04fig9.PNG": {
     "image/png": "[encoded data, 5260 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- You need to print a value for each component. \n",
    "- This requires a second loop. \n",
    "![ch04fig9.PNG](attachment:ch04fig9.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- This loop must be placed inside the preceding loop. We say that the inner loop is <font color='blue'>**nested**</font> inside the outer loop. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Nested Loop"
   ]
  },
  {
   "attachments": {
    "ch04fig10.PNG": {
     "image/png": "[encoded data, 37600 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "![ch04fig10.PNG](attachment:ch04fig10.PNG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Side Note Regarding the `print` Function\n",
    "- The `print` function displays an end of line by default.\n",
    "- If we want to change this behavior, we can set the `end` parameter to another string.\n",
    "    - The default value of the `end` parameter is \\n.\n",
    "- Consider the following example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ICS 104@KFUPM\n"
     ]
    }
   ],
   "source": [
    "course = \"ICS 104\"\n",
    "University = \"KFUPM\"\n",
    "print(course, end = \"@\")\n",
    "print(University)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Nested Loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "#  This program prints a table of powers of x.\n",
    "# Initialize constant variables for the max ranges.\n",
    "NMAX = 4\n",
    "XMAX = 10\n",
    "\n",
    "# Print table header.      \n",
    "for n in range(1, NMAX + 1) :\n",
    "    print(\"%10d\" % n, end=\"\")\n",
    "\n",
    "print()\n",
    "for n in range(1, NMAX + 1) :\n",
    "    print(\"%10s\" % \"x \", end=\"\")\n",
    "\n",
    "print(\"\\n\", \"    \", \"-\" * 35)\n",
    "\n",
    "# Print table body.\n",
    "for x in range(1, XMAX + 1) :   \n",
    "   # Print the x row in the table.\n",
    "    for n in range(1, NMAX + 1) :   \n",
    "        print(\"%10.0f\" % x ** n, end=\"\")\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Processing Strings\n",
    "- A common use of loops is to process or evaluate strings.\n",
    "- For example, you may need to count the number of occurrences of one or more characters in a string or verify that the contents of a string meet certain criteria. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Counting Matches\n",
    "- For example, suppose you need to count the number of uppercase letters contained in a string. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The number of uppercase letters are: 3\n"
     ]
    }
   ],
   "source": [
    "string = \"This is a Test Message\"\n",
    "uppercase = 0\n",
    "for char in string:\n",
    "    if char.isupper():\n",
    "        uppercase = uppercase + 1\n",
    "print(\"The number of uppercase letters are:\",uppercase)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Finding All Matches\n",
    "- For example, suppose you are asked to print the position of each uppercase letter in a sentence. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter a sentence: This is a Test Message\n",
      "0\n",
      "10\n",
      "15\n"
     ]
    }
   ],
   "source": [
    "sentence = input(\"Enter a sentence: \")\n",
    "for i in range(len(sentence)):\n",
    "    if sentence[i].isupper():\n",
    "        print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Finding the First or Last Match\n",
    "- When you count the value that fulfills a condition, you need to look at all values.\n",
    "- However, if your task is to find a match, then you can stop as soon as the condition is fulfilled. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First digit occurs at position 1\n"
     ]
    }
   ],
   "source": [
    "string = \"A1\"\n",
    "found = False\n",
    "position = 0\n",
    "while not found and position < len(string):\n",
    "    if string[position].isdigit():\n",
    "        found = True\n",
    "    else:\n",
    "        position = position + 1\n",
    "if found:\n",
    "    print(\"First digit occurs at position\",position)\n",
    "else:\n",
    "    print(\"The string does not contain a digit.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Processing Strings - Student Activity\n",
    "- What if we need to find the position of the last digit in the string?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Last digit occurs at position 3\n"
     ]
    }
   ],
   "source": [
    "string = \"A1B2\"\n",
    "found = False\n",
    "position = len(string) -1\n",
    "while not found and position >=0:\n",
    "    if string[position].isdigit():\n",
    "        found = True\n",
    "    else:\n",
    "        position = position -1\n",
    "if found:\n",
    "    print(\"Last digit occurs at position\",position)\n",
    "else:\n",
    "    print(\"The string does not contain a digit.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Processing Strings - Student Activity\n",
    "- It is important to validate user input before it is used in computations. \n",
    "- But data validation is not limited to verifying that user input is a specific value or falls within a valid range.\n",
    "- It is also common to require user input to be entered in a specific format.\n",
    "- For example, consider the task of verifying whether a string contains a correctly formatted telephone number.\n",
    "    - In USA, telephone numbers consist of three parts, area code, exchange, and line number <font color='blue'>**(###)###-####**</font>. \n",
    "- Hint: We will need a loop that can exit early if an invalid character or an out of place symbol is encountered while processing the string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "string = \"(323)570-1234\"\n",
    "valid = len(string) == 13\n",
    "position = 0\n",
    "while valid and position < len(string):\n",
    "    if position == 0:\n",
    "        valid = string[position] == \"(\"\n",
    "    elif position == 4:\n",
    "        valid = string[position] == \")\"\n",
    "    elif position == 8:\n",
    "        valid = string[position] == \"-\"\n",
    "    else:\n",
    "        valid = string[position].isdigit()\n",
    "    position = position + 1\n",
    "if valid:\n",
    "    print(\"The string contains a valid phone number.\")\n",
    "else:\n",
    "    print(\"The string does not contain a valid phone number\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Processing Strings: Slices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- Sometimes, we are interested in looking at a part of a string.  \n",
    "- For example, assume that we would like to extract the area code from the telephone number.\n",
    "    - For `phoneNumber = \"(323)570-1234\"`, we would like to extract `323`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- This can be done through a `for` loop or a `while` loop."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- However, the code will have too many statements. Can you implement it?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "## Finding the area code without using the slice operator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- This can be achieved using the `slice` operator, **[`:`]**. For example,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The area code is 323\n"
     ]
    }
   ],
   "source": [
    "## Finding the area code using the slice operator\n",
    "phoneNumber = \"(323)570-1234\"\n",
    "areaCode = phoneNumber[1:4]\n",
    "print(\"The area code is \"+ areaCode)"
   ]
  },
  {
   "attachments": {
    "ch04fig16.PNG": {
     "image/png": "[encoded data, 8880 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Examples\n",
    "- The following examples show the various uses of the slice operator\n",
    "![ch04fig16.PNG](attachment:ch04fig16.PNG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "Name = \"Abdullah Salem Al-Saleh\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Abdullah\n"
     ]
    }
   ],
   "source": [
    "print(Name[0:8])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Abdullah\n"
     ]
    }
   ],
   "source": [
    "print(Name[:8])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Salem Al-Saleh\n"
     ]
    }
   ],
   "source": [
    "print(Name[9:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "cell_style": "split",
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hamla\n"
     ]
    }
   ],
   "source": [
    "print(Name[7:22:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Application: Random Numbers and Simulations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- A simulation program uses the computer to simulate an activity in the real world.\n",
    "- Simulations are commonly used for predicting climate change, analyzing traffic, picking stocks, and many other applications in science and business. \n",
    "- In many simulations, one or more loops are used to modify the state of a system and observe the change. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Generating Random Numbers\n",
    "- Many events in the real world are difficult to predict with absolute precision, yet we can sometimes know the average behavior quite well.\n",
    "- For example, a store may know from experience that a customer arrives every five minutes. \n",
    "    - Of course, that is an average—customers don’t arrive in five minute intervals. \n",
    "    - To accurately model customer traffic, you want to take that random fluctuation into account. \n",
    "    - Now, how can you run such a simulation in the computer?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### The `random` function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "- The Python library has a random number generator that produces numbers that appear to be completely random.\n",
    "- Calling random() yields a random floating-point number that is ≥ 0 and < 1. \n",
    "- Call random() again, and you get a different number. \n",
    "- The random function is defined in the random module."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9902677915849807\n",
      "0.8860373893124276\n",
      "0.0034854952996277166\n",
      "0.9663345553792838\n",
      "0.39472924376777563\n",
      "0.17150040786659804\n",
      "0.43670511967521175\n",
      "0.1289067608783654\n",
      "0.8601857385432646\n",
      "0.33055222904405523\n"
     ]
    }
   ],
   "source": [
    "from random import random\n",
    "for i in range(10):\n",
    "    value = random()\n",
    "    print(value)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### The `randint` function\n",
    "- For example, to simulate the throw of a die, you need random integers\n",
    "between 1 and 6.\n",
    "- Hint: Python provides a separate function for generating a random integer within a given range: \n",
    "    - `randint(a,b)`   # generates an integer from $\\{a, a+1, a+2, ... , b-1, b\\}$ \"randomly\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "outputs": [],
   "source": [
    "#  This program simulates tosses of a pair of dice.\n",
    "from random import randint\n",
    "\n",
    "for i in range(10) :\n",
    "    # Generate two random numbers between 1 and 6, inclusive.   \n",
    "    d1 = randint(1, 6)\n",
    "    d2 = randint(1, 6)\n",
    "  \n",
    "    # Print the two values.   \n",
    "    print(d1, d2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Summary\n",
    "- while loops\n",
    "- for loops\n",
    "- while loops are very commonly used (general purpose)\n",
    "- Uses of the for loop:\n",
    "    - The for loop can be used to iterate over the contents of any container. \n",
    "    - A for loop can also be used as a count-controlled loop that iterates over a range of integer values. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Summary\n",
    "- Each loop requires the following steps:\n",
    "    - Initialization (setup variables to start looping)\n",
    "    - Condition (test if we should execute loop body)\n",
    "    - Update (change something each time through)\n",
    "- A loop executes instructions repeatedly while a condition is True.\n",
    "- Avoid infinite loops.\n",
    "- Loops are commonly used to process strings\n",
    "- Loops are also used to generate pseudo-random numbers for simulation purposes."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "rise": {
   "theme": "yellow"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
